package cn.signalpha.modules.system.controller;


import cn.signalpha.common.cache.CacheNames;
import cn.signalpha.common.constant.AppConstant;
import cn.signalpha.core.cache.utils.CacheUtil;
import cn.signalpha.core.excel.util.ExcelUtil;
import cn.signalpha.core.mp.support.Condition;
import cn.signalpha.core.mp.support.Query;
import cn.signalpha.core.redis.cache.RedisCache;
import cn.signalpha.core.secure.TokenUser;
import cn.signalpha.core.secure.annotation.PreAuth;
import cn.signalpha.core.tool.api.R;
import cn.signalpha.core.tool.constant.RoleConstant;
import cn.signalpha.core.tool.constant.SystemConstant;
import cn.signalpha.core.tool.utils.DateUtil;
import cn.signalpha.core.tool.utils.Func;
import cn.signalpha.core.tool.utils.StringUtil;
import cn.signalpha.modules.system.entity.User;
import cn.signalpha.modules.system.excel.UserExcel;
import cn.signalpha.modules.system.excel.UserImporter;
import cn.signalpha.modules.system.service.IUserService;
import cn.signalpha.modules.system.vo.UserVO;
import cn.signalpha.modules.system.wrapper.UserWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import static cn.signalpha.core.cache.constant.CacheConstant.USER_CACHE;

/**
 * 控制器
 */
@RestController
@RequestMapping(AppConstant.APPLICATION_SYSTEM_NAME + "/admin/user")
@AllArgsConstructor
public class UserController {

	private final RedisCache redisCache;
	private final IUserService userService;

	@GetMapping("/page")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "name", value = "姓名", paramType = "query", dataType = "string"),
		@ApiImplicitParam(name = "account", value = "账号名", paramType = "query", dataType = "string"),
	})
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "分页", notes = "传入account和name")
	@PreAuth(RoleConstant.HAS_ROLE_ADMIN)
	public R<IPage<UserVO>> page(@ApiIgnore User user, Query query, Long deptId) {
		IPage<User> pages = userService.selectUserPage(Condition.getPage(query), user, deptId);
		return R.data(UserWrapper.build().pageVO(pages));
	}

	@GetMapping("/list")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "name", value = "姓名", paramType = "query", dataType = "string"),
		@ApiImplicitParam(name = "account", value = "账号名", paramType = "query", dataType = "string"),
	})
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "列表", notes = "传入account和name")
	@PreAuth(RoleConstant.HAS_ROLE_ADMIN)
	public R<IPage<UserVO>> list(@ApiIgnore @RequestParam Map<String, Object> user, Query query) {
		QueryWrapper<User> queryWrapper = Condition.getQueryWrapper(user, User.class);
		IPage<User> pages = userService.page(Condition.getPage(query), queryWrapper);
		return R.data(UserWrapper.build().pageVO(pages));
	}

	@GetMapping("/info")
	@ApiOperationSupport(order = 10)
	@ApiOperation(value = "详情", notes = "传入id")
	public R<UserVO> info(TokenUser user) {
		User detail = userService.getById(user.getUserId());
		return R.data(UserWrapper.build().entityVO(detail));
	}

	@GetMapping("/detail")
	@ApiOperationSupport(order = 11)
	@ApiOperation(value = "详情", notes = "")
	@PreAuth(RoleConstant.HAS_ROLE_ADMIN)
	public R<UserVO> detail(User user) {
		User detail = userService.getOne(Condition.getQueryWrapper(user));
		return R.data(UserWrapper.build().entityVO(detail));
	}

	@PostMapping("/submit")
	@ApiOperationSupport(order = 20)
	@ApiOperation(value = "新增或修改", notes = "传入User")
	@PreAuth(RoleConstant.HAS_ROLE_ADMIN)
	public R submit(@Valid @RequestBody User user) {
		CacheUtil.clear(USER_CACHE);
		return R.status(userService.submit(user));
	}

	@PostMapping("/update")
	@ApiOperationSupport(order = 21)
	@ApiOperation(value = "修改", notes = "传入User")
	public R update(@Valid @RequestBody User user) {
		CacheUtil.clear(USER_CACHE);
		return R.status(userService.updateUser(user));
	}

	@PostMapping("/grant")
	@ApiOperationSupport(order = 22)
	@ApiOperation(value = "权限设置", notes = "传入roleId集合以及menuId集合")
	@PreAuth(RoleConstant.HAS_ROLE_ADMIN)
	public R grant(@ApiParam(value = "userId集合", required = true) @RequestParam String userIds,
				   @ApiParam(value = "roleId集合", required = true) @RequestParam String roleIds) {
		boolean temp = userService.grant(userIds, roleIds);
		return R.status(temp);
	}

	@PostMapping("/reset-password")
	@ApiOperationSupport(order = 23)
	@ApiOperation(value = "初始化密码", notes = "传入userId集合")
	@PreAuth(RoleConstant.HAS_ROLE_ADMIN)
	public R resetPassword(@ApiParam(value = "userId集合", required = true) @RequestParam String userIds) {
		boolean temp = userService.resetPassword(userIds);
		return R.status(temp);
	}

	@PostMapping("/unlock")
	@ApiOperationSupport(order = 24)
	@ApiOperation(value = "账号解锁", notes = "传入id")
	public R unlock(String userIds) {
		if (StringUtil.isBlank(userIds)) {
			return R.fail("请至少选择一个用户");
		}
		List<User> userList = userService.list(Wrappers.<User>lambdaQuery().in(User::getId, Func.toLongList(userIds)));
		userList.forEach(user -> redisCache.del(CacheNames.cacheKey(CacheNames.USER_FAIL_KEY, user.getAccount())));
		return R.success("操作成功");
	}

	@PostMapping("/update-password")
	@ApiOperationSupport(order = 25)
	@ApiOperation(value = "修改密码", notes = "传入密码")
	public R updatePassword(TokenUser user, @ApiParam(value = "旧密码", required = true) @RequestParam String oldPassword,
							@ApiParam(value = "新密码", required = true) @RequestParam String newPassword,
							@ApiParam(value = "新密码", required = true) @RequestParam String newPassword1) {
		boolean temp = userService.updatePassword(user.getUserId(), oldPassword, newPassword, newPassword1);
		return R.status(temp);
	}

	@PostMapping("/update-info")
	@ApiOperationSupport(order = 26)
	@ApiOperation(value = "修改基本信息", notes = "传入User")
	public R updateInfo(@Valid @RequestBody User user) {
		CacheUtil.clear(USER_CACHE);
		return R.status(userService.updateUserInfo(user));
	}

	@PostMapping("import-user")
	@ApiOperationSupport(order = 30)
	@ApiOperation(value = "导入用户", notes = "传入excel")
	public R importUser(MultipartFile file, Integer isCovered) {
		UserImporter userImporter = new UserImporter(userService, isCovered == 1);
		ExcelUtil.save(file, userImporter, UserExcel.class);
		return R.success("操作成功");
	}

	@GetMapping("export-user")
	@ApiOperationSupport(order = 31)
	@ApiOperation(value = "导出用户", notes = "传入user")
	public void exportUser(@ApiIgnore @RequestParam Map<String, Object> user, HttpServletResponse response) {
		QueryWrapper<User> queryWrapper = Condition.getQueryWrapper(user, User.class);
		queryWrapper.lambda().eq(User::getIsDeleted, SystemConstant.DB_NOT_DELETED);
		List<UserExcel> list = userService.exportUser(queryWrapper);
		ExcelUtil.export(response, "用户数据" + DateUtil.time(), "用户数据表", list, UserExcel.class);
	}

	@GetMapping("export-template")
	@ApiOperationSupport(order = 32)
	@ApiOperation(value = "导出模板")
	public void exportUser(HttpServletResponse response) {
		List<UserExcel> list = new ArrayList<>();
		ExcelUtil.export(response, "用户数据模板", "用户数据表", list, UserExcel.class);
	}

	@PostMapping("/remove")
	@ApiOperationSupport(order = 50)
	@ApiOperation(value = "删除", notes = "传入id集合")
	@PreAuth(RoleConstant.HAS_ROLE_ADMIN)
	public R remove(@RequestParam String ids) {
		CacheUtil.clear(USER_CACHE);
		return R.status(userService.removeUser(ids));
	}

}
